﻿using UnityEngine;
using UnityEngine.UI;

[shaco.UILayerOpenAsync]
public class SettingLayer : UnityEngine.MonoBehaviour
{
    public Image imageBackgroud;

    public Button buttonBack;
    public Button buttonChangeToChinese;
    public Button buttonChangeToEnglish;

    public Slider sliderBGM;
    public Slider sliderSE;
    public Slider sliderVoice;

    void OnUIOpen(shaco.Base.BaseEventArg arg)
    {
        //点击返回按钮
        this.buttonBack.onClick.AddListener(() => this.CloseMe());

        //点击切换中文按钮
        this.buttonChangeToChinese.onClick.AddListener(() =>
        {
            shaco.GameHelper.localization.ChangeLanguage(UnityEngine.SystemLanguage.Chinese, ShootMan.GameEntry.UpdateLocalization);
            shaco.GameHelper.datasave.WriteEnum(ShootMan.GlobalDefines.SettingKeys.CURRENT_LANGUAGE, UnityEngine.SystemLanguage.Chinese);
        });

        //点击切换英文按钮
        this.buttonChangeToEnglish.onClick.AddListener(() =>
        {
            shaco.GameHelper.localization.ChangeLanguage(UnityEngine.SystemLanguage.English, ShootMan.GameEntry.UpdateLocalization);
            shaco.GameHelper.datasave.WriteEnum(ShootMan.GlobalDefines.SettingKeys.CURRENT_LANGUAGE, UnityEngine.SystemLanguage.English);
        });

        //设置当前音量
        this.LoadVolume();
        this.sliderBGM.value = shaco.GameHelper.music.volume;
        this.sliderSE.value = shaco.GameHelper.sound.volume;
        this.sliderVoice.value = shaco.GameHelper.voice.volume;

        //动态设置背景图片
        var loadPath = "Assets/ShootMan/Resources_Solid/UI/UI__NoAtlas/Sign_in_bg1_Texture_1.png";
        var request = shaco.GameHelper.res.LoadAsync<UnityEngine.Sprite>(loadPath);
        request.OnCompleted(v =>
        {
            shaco.Log.Info("load sprite asyc test result", request.assetObject);
            this.imageBackgroud.sprite = request.assetObject as Sprite;
            request.Release();
        });
    }

    void OnUIClose()
    {
        this.SaveVolume();
    }

    void SaveVolume()
    {
        shaco.GameHelper.datasave.WriteFloat("GlobalBGM.Volume", this.sliderBGM.value);
        shaco.GameHelper.datasave.WriteFloat("GlobalSE.Volume", this.sliderSE.value);
        shaco.GameHelper.datasave.WriteFloat("GlobalVoice.Volume", this.sliderVoice.value);
    }

    void LoadVolume()
    {
        shaco.GameHelper.music.SetVolume(shaco.GameHelper.datasave.ReadFloat("GlobalBGM.Volume", shaco.GameHelper.music.volume));
        shaco.GameHelper.sound.SetVolume(shaco.GameHelper.datasave.ReadFloat("GlobalSE.Volume", shaco.GameHelper.sound.volume));
        shaco.GameHelper.voice.SetVolume(shaco.GameHelper.datasave.ReadFloat("GlobalVoice.Volume", shaco.GameHelper.voice.volume));
    }
}